package com.hsd.netty.server.decoder;

import com.google.gson.Gson;
import com.hsd.netty.server.common.NettyHeader;
import com.hsd.netty.server.common.NettyMessage;
import com.hsd.netty.server.model.RequestObject;
import com.hsd.netty.server.strategy.MessageHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
/**
 * @author s.he
 * on 2020/6/1
 */
@Deprecated
public class NettyCommonMessageDecoder  extends MessageToMessageDecoder<NettyMessage> {
    @Autowired
    private MessageHandlerAdapter messageHandlerAdapter;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, NettyMessage nettyMessage, List<Object> list) throws Exception {
        NettyHeader nettyHeader = nettyMessage.getNettyHeader();
        byte type = nettyHeader.getType();
        String body = nettyMessage.getBody();
        NettyMessage result = messageHandlerAdapter.handler(type, channelHandlerContext, nettyMessage);
        //如果是心跳和登录，则直接在这边返回，如果是正常的请求报文，则需要跳转到下一个节点
        if(result.getNettyHeader() != null) {
            channelHandlerContext.channel().writeAndFlush(result);
            return;
        } else  {
            Gson gson = new Gson();
            RequestObject requestObject = gson.fromJson(body, RequestObject.class);
            list.add(requestObject);
        }
    }
}
